package com.hy.mvc.biz.utils;

import com.hy.mvc.web.conroller.RedisController;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * html תPDF
 * @author wb-hyl282156
 */
public class PDFUtils {

    private static final Logger logger = LoggerFactory.getLogger(RedisController.class);

    public static void genContractPDF(byte[] data, OutputStream out) throws Exception {
        // String css = ".underline{text-decoration:underline;}";
        genPDF(data, null, out);
    }

    public static void genPDF(byte[] data, String css, OutputStream out) throws Exception {
        // step 1
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, out);
        // step 3
        document.open();

        InputStream cssIs = null;
        if (css != null) {
            cssIs = new ByteArrayInputStream(css.getBytes());
        }
        // step 4
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
            new ByteArrayInputStream(data), cssIs, Charset.forName("UTF-8"), new MyFontsProvider());
        // step 5
        try {
            document.close();
        } catch (Exception e) {

        }
    }

    public static class MyFontsProvider extends XMLWorkerFontProvider {
        public MyFontsProvider() {
            super(null, null);
        }

        @Override
        public Font getFont(final String fontname, String encoding, float size, final int style) {
            BaseFont bf = null;
            try {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            } catch (Exception e) {
                logger.error("get font err",e);
                e.printStackTrace();
            }
            Font font = new Font(bf, size, style);
            return font;
        }
    }

}
